local Networking = Tubes.Networking
local NetMessage = {}
NetMessage.__index = NetMessage

Networking.NetMessage = Tubes.MakeConstructor (NetMessage)

function NetMessage:ctor (name, recipients)
	self.Name = name
	self.Buffer = ""
end

function NetMessage:BitField (...)
	local Bits = {...}
	local Value = 0
	local Weight = 1
	for i = 1, 8 do
		if Bits [i] then
			Value = Value + Weight
		end
		Weight = Weight * 2
	end
	self:UChar (Value)
end

function NetMessage:Char (value)
	self:UChar (value + 128)
end

function NetMessage:End ()
	local Buffer = self.Buffer
	while Buffer:len () > 0 do
		RunConsoleCommand ("tubes_transfer", Buffer:sub (1, 100))
		Buffer = Buffer:sub (101)
	end
	RunConsoleCommand ("tubes_transfer_end", tostring (Networking.StringPool:LookupStringIndex (self.Name, true)))
end

function NetMessage:Player (value)
	if type (value) ~= "Player" then
		self:UChar (254)
		return
	end
	self:UChar (value:EntIndex () + 16)
end

function NetMessage:Short (value)
	self:UShort (value + 32768)
end

function NetMessage:String (value)
	value = value:gsub ("[\t\r\n\1\2]", function (char)
		return "\1" .. string.char (string.byte (char) + 16)
	end)
	self.Buffer = self.Buffer .. value .. string.char (2)
end

function NetMessage:UChar (value)
	if Networking.BadChars [value] then
		self.Buffer = self.Buffer .. string.char (255) .. Networking.BadChars [value]
	else
		self.Buffer = self.Buffer .. string.char (value)
	end
end

function NetMessage:UShort (value)
	local Part = value & 63
	value = math.floor (value / 64)
	if value == 0 then
		self.Buffer = self.Buffer .. string.char (192 + Part)
		return
	end
	self.Buffer = self.Buffer .. string.char (128 + Part)
	Part = value & 63
	value = math.floor (value / 64)
	if value == 0 then
		self.Buffer = self.Buffer .. string.char (192 + Part)
		return
	end
	self.Buffer = self.Buffer .. string.char (128 + Part)
	Part = value & 63
	self.Buffer = self.Buffer .. string.char (192 + Part)
end